package com.example.yichuangyun.service;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.provider.CallLog;
import android.telephony.PhoneStateListener;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;

import com.example.yichuangyun.application.MyApplication;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.utils.AppUtils;
import com.example.yichuangyun.utils.FileUtil;
import com.example.yichuangyun.utils.ToastHelper;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class MyPhoneService extends Service {
    private static final String TAG = "@@@@@@@@PhoneService";
    private final String[] projection = {CallLog.Calls.CACHED_NAME // 通话记录的联系人
            , CallLog.Calls.NUMBER // 通话记录的电话号码
            , CallLog.Calls.DATE // 通话记录的日期
            , CallLog.Calls.DURATION // 通话时长
            , CallLog.Calls.TYPE}; // 通话类型

    private final Handler handler = new Handler();
    private TelephonyManager telephonyManager;
    private final List<PhoneStateListener> phoneListeners = new ArrayList<>();

    private Notification notification;
    private boolean isOpen = true;
    private int versionCode;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        versionCode = AppUtils.getVersionCode(this);
        // 8.0 以上需要特殊处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            nm.createNotificationChannel(new NotificationChannel("10", "App Service", NotificationManager.IMPORTANCE_DEFAULT));
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "10");
        notification = builder.setContentText("service被设为前台进程！").setPriority(NotificationCompat.PRIORITY_MAX).setCategory(Notification.CATEGORY_SERVICE).build();

        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        SubscriptionManager subscriptionManager = (SubscriptionManager) getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        // 获取所有SIM卡信息
        List<SubscriptionInfo> subscriptionInfos = subscriptionManager.getActiveSubscriptionInfoList();
        if (subscriptionInfos != null) {
            for (SubscriptionInfo info : subscriptionInfos) {
                int subscriptionId = info.getSubscriptionId();
                // 为每个SIM卡注册监听器
                PhoneStateListener phoneListener = new MyPhoneListener();
                phoneListeners.add(phoneListener);
                telephonyManager.createForSubscriptionId(subscriptionId).listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
            }
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(2, notification);
        return START_STICKY;
    }

    private final class MyPhoneListener extends PhoneStateListener {

        public MyPhoneListener() {
        }

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING: // 零响状态1
                    isOpen = false;
                    Log.e(TAG, "手机状态：来电:" + incomingNumber);
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK: // 通话状态2
                    Log.e(TAG, "手机状态：接听");
                    isOpen = false;
                    break;
                case TelephonyManager.CALL_STATE_IDLE:  // 挂掉电话0
                    Log.e(TAG, "手机状态：空闲");
                    if (!isOpen) {
                        if (MyApplication.manager.isLogin()) {
                            // 通话记录可能不会立即写入数据库，建议稍作延迟再查询
                            handler.postDelayed(MyPhoneService.this::getLastCallLog, 2000);
                        }
                    }
                    break;
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    }

    @SuppressLint("Range")
    private void getLastCallLog() {
        int timeRangeMs = 60 * 60 * 1000; // 1小时的毫秒数
        // 计算时间范围起点(当前时间 - 指定时间范围)
        long startTime = System.currentTimeMillis() - timeRangeMs;
        // 查询条件：日期 >= 开始时间
        String selection = CallLog.Calls.DATE + " >= ?";
        String[] selectionArgs = new String[]{String.valueOf(startTime)};// 计算时间范围起点(当前时间 - 指定时间范围)
        try (Cursor cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, projection, selection, selectionArgs, CallLog.Calls.DEFAULT_SORT_ORDER)) { // 按时间降序排序

            if (cursor != null && cursor.moveToFirst()) { // 只取第一条记录
                String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER)); //号码
                int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE)); //通话类型：1.呼入2.呼出3.未接
                long date = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE)); //通话日期
                int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION)); //通话时长，值为多少秒
                String callDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date(date));
                Log.e("@@@@@type--->", type + ",   duration--->" + duration + ",   number--->" + number + "======" + date);
                switch (type) {
                    case 1: // 来电（呼入）
                        if (duration == 0) { // 未接
                            uploadCallRecord(number, 3, callDate, 0, 3, null);
                        } else { // 已接
                            alreadyLineUpload(number, callDate, duration, type);
                        }
                        break;
                    case 2: // 去电
                        if (duration > 0) { // 已接
                            alreadyLineUpload(number, callDate, duration, type);
                        } else { // 未接
                            uploadCallRecord(number, 2, callDate, 0, type, null);
                        }
                        break;
                    case 3: // 未接（对方挂断）
                    case 5: // 未接（本机挂断）
                        uploadCallRecord(number, 3, callDate, 0, 3, null);
                        break;
                    default:
                        // 处理未知类型
                        Log.e(TAG, "未知通话类型: " + type);
                        break;
                }
            }
        } catch (SecurityException e) {
            Log.e(TAG, "无权限读取通话记录: " + e.getMessage());
        }
    }

    /**
     * 上传通话录音文件
     */
    private void alreadyLineUpload(String number, String date, int duration, int type) {
        List<File> files = FileUtil.searchFiles(FileUtil.getFile());
        if (!files.isEmpty()) {
            // 最大值下标，找到最新的录音文件
            int maxIndex = 0;
            for (int i = 0; i < files.size(); i++) {
                // lastModified()：最后一次修改的时间
                if (files.get(i).lastModified() > files.get(maxIndex).lastModified()) {
                    maxIndex = i;
                }
            }
            uploadCallRecord(number, 2, date, duration, type, files.get(maxIndex).getName().replaceAll(" +", "").contains(number) ? files.get(maxIndex) : null);
        } else {
            uploadCallRecord(number, 2, date, duration, type, null);
        }
    }

    /**
     * 上传通话记录
     *
     * @param telNumber 电话号码
     * @param channel   渠道
     * @param trackTime 通话时间
     * @param callSec   通话时长
     * @param callType  通话类型：1来电，2去电；3未接
     * @param file      通话录音文件
     */
    private void uploadCallRecord(final String telNumber, int channel, final String trackTime, final Integer callSec, final Integer callType, final File file) {
        Log.e("@@@@@@@@", file == null ? "file=null" : " file not null：" + file.getName());
        long currentTime = System.currentTimeMillis();
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("telNumber", telNumber);
            requestDate.put("channel", channel);
            requestDate.put("trackTime", trackTime);
//            if (callSec > 0 && file != null && file.exists()) {
//                requestDate.put("linkedid", currentTime + telNumber + versionCode); // 文件名
//            }
            requestDate.put("callSec", callSec);
            requestDate.put("callType", callType);
            requestDate.put("serviceType", Constant.pushServiceType); // 默认1:商机，预留字段
            requestDate.put("serviceId", Constant.pushBusinessId); // 发起拨号商机ID
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().uploadCallRecord(requestBody), new MyObserver<HttpRespond<String>>() {
            @Override
            protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                if (stringHttpRespond.code == Constant.SUCCESS) {
                    ToastHelper.show("通话记录已成功上传");
                    if (callSec > 0 && file != null && file.exists()) {
                        uploadFile(file, currentTime + telNumber + versionCode, stringHttpRespond.data);
                    }
                    EventBus.getDefault().post(new EventBusModel(Constant.refreshTodayData));
                } else {
                    ToastHelper.show(stringHttpRespond.msg);
                }
                Constant.pushBusinessId = "";
                Constant.pushServiceType = 1;
            }

            @Override
            protected void onFail(Throwable e) {
                super.onFail(e);
                Constant.pushBusinessId = "";
                Constant.pushServiceType = 1;
            }
        });
    }

    /**
     * 上传录音文件
     */
    private void uploadFile(File file, String linkedId, String id) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", linkedId, requestBody);
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().uploadRecordFile(part, id), new MyObserver<HttpRespond<String>>() {
            @Override
            protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                if (Constant.SUCCESS == stringHttpRespond.code) {
                    ToastHelper.show("录音文件已成功上传");
                    if (file.exists()) {
                        file.delete();
                    }
                } else {
                    ToastHelper.show(stringHttpRespond.msg);
                }
            }

            @Override
            protected void onFail(Throwable e) {
                super.onFail(e);
                ToastHelper.show(e.getMessage());
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
        if (telephonyManager != null) {
            for (PhoneStateListener listener : phoneListeners) {
                telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
            }
        }
        handler.removeCallbacksAndMessages(null);
    }
}

